System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

68% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Day 10: Software Infrastructure
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design a Code Deployment System
Image

Here is the detailed step-by-step system design for a Code Deployment System.

1. Problem Definition and Scope

We are designing a centralized system that automates the deployment of software artifacts (like binaries, JARs, or Docker images) to a large fleet of servers. This system bridges the gap between "Continuous Integration" (building the code) and "Production" (running the code).

  • User Groups:

    • Developers: Trigger deployments, monitor rollout progress, and rollback if bugs appear.

    • Ops/SRE: Configure deployment groups (e.g., "Staging", "Prod-East") and safety thresholds.

    • Agents: The software running on the target servers that executes the installation commands.

  • Main Actions: Deploy a specific version to a group, monitor status, and rollback.

  • Scope:

    • In Scope: Deployment orchestration logic (rolling updates), agent management, and state tracking.

    • Out of Scope: The "Build" process (CI), source code management, and server provisioning (Terraform). We assume the artifact is already built and stored in S3.

Image

2. Clarify functional requirements

Must Have:

  • Deployment Trigger: Users can deploy a specific version (e.g., v1.2) to a specific group of servers.

  • Rolling Updates: The system must update servers in batches (e.g., 10 at a time) to ensure zero downtime.

  • Agent-based Execution: A lightweight agent on the target server pulls instructions and runs them (avoids SSH/firewall issues).

  • Real-time Status: Users can see exactly how many servers have succeeded, failed, or are in progress.

  • Automatic Rollback: If the failure rate exceeds a threshold (e.g., > 10%), automatically stop and revert.

  • History & Auditing: Keep a permanent record of who deployed what and when.

Nice to Have:

  • Canary Deployments: Deploy to 1% of hosts first, wait for health metrics, then proceed.

  • Deployment Scripts: Support custom pre-install and post-install hooks.

Image

3. Clarify non-functional requirements

  • Target Users: Large engineering organization.

    • Scale: 10,000 target servers. 500 deployments per day.
  • Read/Write Pattern:

    • Control Plane: Read-heavy for users checking status. Write-heavy for agents reporting "heartbeats" (status updates).
  • Latency:

    • API: < 200ms for UI interactions.
    • Propagation: An agent should pick up a new deployment command within 15–30 seconds.
  • Availability: 99.9% for the control plane. If the deployment system is down, production apps keep running, but we cannot ship fixes.

  • Consistency: Strong consistency for deployment state. We must know the exact version running on every host.

  • Network: Bandwidth usage will be the main constraint during large deployments (distributing large binaries).

Image

4. Back of the envelope estimates

  • Throughput (QPS):
    • Heartbeats: 10,000 agents pinging every 10 seconds.
    • requests per second (RPS). This is a constant background load.
    • Deployments: 500/day is negligible QPS for the API triggers.
  • Storage (Artifacts):
    • Average artifact size: 500 MB.
    • 500 deploys/day * 500 MB = 250 GB/day.
    • This fits easily in Object Storage (S3), but bandwidth is the concern.
  • Bandwidth (The Bottleneck):
    • If we deploy to 1,000 servers simultaneously:
    • of data transfer.
    • If this happens in 60 seconds, that is . We cannot serve this from our API servers; agents must download from S3/CDN directly.
Image

5. API design

We will use a REST API for the Control Plane.

1. Create Deployment

  • POST /api/v1/deployments
  • Request:
{ "service\_id": "payment-service", "version": "v2.0", "group\_id": "prod-us-east", "strategy": "rolling", "batch\_size": 10 }
  • Response: { "id": "dep_101", "status": "PENDING" }

2. Get Deployment Status

  • GET /api/v1/deployments/{id}
  • Response:
{ "status": "IN\_PROGRESS", "stats": { "success": 45, "failed": 0, "total": 100 }, "current\_batch": \["host-1", "host-2"\] }

3. Agent Heartbeat (Internal)

  • POST /api/v1/agents/heartbeat
  • Request: { "host_id": "host_A", "current_version": "v1.0", "status": "HEALTHY" }
  • Response:
    • If no work: { "command": "noop" }
    • If update needed: { "command": "deploy", "version": "v2.0", "artifact_url": "s3://bucket/v2.0.zip", "task_id": "task_555" }

4. Update Task Result

  • PUT /api/v1/tasks/{task_id}
  • Request: { "status": "SUCCESS", "logs_url": "s3://logs/..." }

6. High level architecture

We will use a Pull-based Architecture. Agents on the servers poll the central system. This avoids the complexity of the server needing to SSH into 10,000 hosts behind different firewalls.

Component Roles:

  1. API Server: Handles user requests (Start Deploy, Get Status).

  2. Orchestrator Worker: The "Brain." It runs in the background. It calculates which servers need to be updated next based on the Rolling Strategy and pushes commands to Redis.

  3. Redis Command Queue: Stores the "Next Action" for agents. This decouples the heavy write logic from the read logic.

  4. Agent Gateway: A lightweight service specifically designed to handle the 1,000+ RPS of heartbeats. It checks Redis for commands to keep latency low.

  5. Database (PostgreSQL): Stores the "Source of Truth" (Deployment History, Groups, Configurations).

  6. Agent: Daemon on the VM. Polls the Gateway, downloads artifacts from S3, and executes install scripts.

Image

7. Data model

We use PostgreSQL because deployment state is relational and transitions must be transactional.

1. Services

  • id (PK), name, health_check_endpoint.

2. Hosts (Inventory)

  • id (PK), hostname, service_id, current_version, last_heartbeat.

3. Deployments (The Intent)

  • id (PK), service_id, target_version, strategy, status (PENDING, RUNNING, COMPLETED, FAILED, ROLLED_BACK).

4. DeploymentTasks (The Progress)

  • Crucial table. One row per host per deployment.

  • id (PK), deployment_id, host_id, status (PENDING, QUEUED, IN_PROGRESS, SUCCESS, FAILED).

  • Index: (deployment_id, status) allows the Orchestrator to quickly query "How many hosts in deployment X are currently running?"

8. Core flows end to end

This section describes the "Rolling Update" lifecycle. This is the mechanism that allows us to update 10,000 servers without taking the entire system offline.

The core design philosophy here is a Pull-Based Architecture. Instead of a central server trying to SSH into 10,000 machines (which is fragile and security-heavy), the 10,000 machines "phone home" to ask for work.

Here is the detailed breakdown of the 5 steps:

Step 1: Initiation (The Intent)

The goal: Record what we want to happen, not make it happen yet.

When a developer clicks "Deploy," the API does not contact any servers. It simply records the "Intent" in the database.

  1. Deployment Record: A row is created in the Deployments table: "Deploy v2.0 to Group A."

  2. Task Explosion: The system looks up Group A, finds 100 hosts, and creates 100 rows in the DeploymentTasks table.

    • Status for all 100 tasks is set to PENDING.
    • Why? This gives us a granular tracking log. We can see exactly which specific host failed later.
Image

Step 2: Orchestration (The Brain)

The goal: Move the fleet forward in safe, small steps.

This is an asynchronous background worker. It doesn't run constantly; it wakes up periodically (e.g., every 5 seconds) to check the state of the world.

  1. The Check: It asks the DB: "Are there any active deployments? How is the current batch doing?"

  2. The Decision:

    • If the previous batch is finished (Status: SUCCESS), it selects the next 10 PENDING hosts.
    • It updates their status in the DB to QUEUED.
  3. The Handoff (Redis): This is a critical performance optimization. The Orchestrator pushes a command ("DEPLOY v2.0") into Redis specifically for those 10 hosts.

    • Why Redis? We don't want 10,000 agents querying our main PostgreSQL database every few seconds. Redis acts as a high-speed "inbox" for the agents.
Image

Step 3: Agent Pickup (The Handshake)

The goal: Agents ask for permission to update.

The servers (Agents) are unaware of the "Deployment" or the "Orchestrator." They only know one thing: Heartbeating.

  1. The Ping: Every 10 seconds, the Agent sends a lightweight HTTP POST to the Agent Gateway.

    • Payload: {"host_id": "host-1", "status": "HEALTHY"}
  2. The Lookup: The Gateway checks Redis: "Is there a pending command in the inbox for host-1?"

    • Scenario A (No Work): Redis is empty. Gateway returns 200 OK {"command": "noop"}.
    • Scenario B (Work Found): Redis has the "DEPLOY" command from Step 2.
  3. The Instruction: The Gateway returns the command along with a Presigned S3 URL.

    • Why Presigned? This allows the Agent to download the heavy binary directly from S3 securely. The API server doesn't have to waste its own bandwidth proxying the file.
Image

Step 4: Execution (The Heavy Lifting)

The goal: Perform the risky operation locally.

The Agent now has its orders. It performs the update logic on its own.

  1. Download: It pulls the 500MB artifact from S3.

  2. The Swap:

    • Stop: Gracefully shuts down the running app (v1.0).
    • Install: Unzips/Docker pulls the new version (v2.0).
    • Start: Launches the new process.
  3. Local Health Check: Before telling the server it's done, the Agent checks itself. It hits localhost:8080/health.

    • If this fails, the Agent can auto-rollback locally immediately to minimize downtime.
Image

Step 5: Completion & Loop (The Feedback)

The goal: Close the loop so the brain can proceed.

  1. Reporting: The Agent sends a final update to the API: PUT /tasks/{id} {status: "SUCCESS"}.

  2. The Loop: The Orchestrator (from Step 2) wakes up again. It sees that the 10 hosts it was waiting for are now marked SUCCESS in the DB.

  3. Next Batch: It picks the next 10 hosts and repeats Step 2.

This cycle continues until all 100 hosts are updated. If at any point the error rate spikes (e.g., 3 out of 10 hosts report FAILED), the Orchestrator stops creating new batches, effectively "freezing" the bad deployment.

Image

9. Caching and read performance

The system faces a "Thundering Herd" of 10,000 agents.

  • Heartbeat Handling:
    • We do not want 1,000 writes/sec to Postgres for simple "I am alive" messages.
    • Strategy: Agents write heartbeats to Redis (SET host:123:last_seen <timestamp>).
    • A background worker syncs these timestamps to Postgres in bulk every minute (Write-Behind pattern).
  • Task Distribution:
    • The Agent Gateway only reads from Redis to check for pending commands. It does not query the DB on every heartbeat. This ensures the gateway is extremely fast.
  • Artifact Caching:
    • CDN: We place CloudFront/Cloudflare in front of S3. Agents download from the nearest edge location, reducing latency and S3 costs.

10. Storage, indexing and media

  • Primary Storage (Postgres):
    • Used for strict state tracking.
    • Indexes: deployment_id (for grouping tasks), host_id (for agent lookups).
  • Artifact Storage (Object Storage/S3):
    • Binaries are opaque blobs to us. We store them in S3.
    • Immutability: Once v1.0.zip is uploaded, it cannot be overwritten. A fix must be v1.1.zip.
  • Logs:
    • Install logs (text) are uploaded by the Agent to S3 (e.g., s3://logs/dep-101/host-5.log).
    • We do not store logs in the DB. The DB only stores the S3 path URL.

11. Scaling strategies

  • Partitioning the DB:
    • The DeploymentTasks table grows fast (100k rows/day).
    • We partition by time (e.g., monthly). Old partitions can be archived to cold storage since we rarely debug deployments from 6 months ago.
  • Agent Gateway Scaling:
    • The Gateway is stateless. We can auto-scale it horizontally behind a Load Balancer to handle 100k+ agents if needed.
  • P2P Artifact Distribution:
    • For 10,000+ servers, even a CDN might be slow or expensive.
    • Strategy: Use a Peer-to-Peer protocol (like BitTorrent or Dragonfly). The first 100 servers download from S3. The next 1,000 download pieces from the first 100. This turns the fleet's bandwidth into an asset.

12. Reliability, failure handling and backpressure

  • Circuit Breaker (Automatic Rollback):
    • The Orchestrator monitors the failure rate of the current batch.
    • Rule: If of hosts in a batch fail, PAUSE the deployment immediately.
    • This prevents a bad config change from taking down the entire fleet.
  • Agent Resilience:
    • If the Agent crashes during an update, it must restart (via systemd/supervisord) and check its local state file. "Was I in the middle of a deploy? Let me retry the health check."
  • Jitter:
    • Agents should not all heartbeat at the exact same millisecond. We add a random delay () to the heartbeat interval to smooth out the load.

13. Security, privacy and abuse

  • Authentication (mTLS):
    • How do we trust the Agent? Mutual TLS. The Agent has a client certificate signed by our internal CA. The Gateway validates this cert before answering.
  • Artifact Integrity (Signing):
    • Security Risk: An attacker compromises S3 and replaces v2.0.zip with malware.
    • Solution: The Build Server signs the artifact with a Private Key. The Agent has the Public Key and verifies the signature before installing.
  • Secrets:
    • Deployment artifacts should not contain secrets (passwords).
    • The Agent should fetch secrets from a dedicated Secret Manager (Vault/AWS Secrets Manager) at runtime.

14. Bottlenecks and next steps

  • Bottleneck: Database Write Throughput.
    • During a massive deployment, thousands of agents might report "Success" simultaneously.
    • Next Step: Use a message queue (Kafka) to buffer status updates before writing to the DB.
  • Bottleneck: Orchestrator Polling.
    • Polling the DB for "Pending" deployments is inefficient at huge scale.
    • Next Step: Move to an Event-Driven architecture where "Task Success" events trigger the Orchestrator immediately.

Summary

  • We designed a Pull-based system resilient to network issues.
  • We decoupled the Control Plane (Orchestrator) from the Data Plane (Agents).
  • We prioritized Safety with rolling updates and automatic circuit breakers.
Design a Live Comment Streaming Service (Twitch Chat)
Design an API Gateway
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Step 1: Initiation (The Intent)

Step 2: Orchestration (The Brain)

Step 3: Agent Pickup (The Handshake)

Step 4: Execution (The Heavy Lifting)

Step 5: Completion & Loop (The Feedback)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary